/*
 * BanBu_NoDisturbingViewController
 * @description 本文件提供推送勿扰模式界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供推送勿扰模式界面的ViewController
 */

#import "BanBu_NoDisturbingViewController.h"
#import "AppDataManager.h"
#import "BanBu_ImageView.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_NavButton.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"


@interface BanBu_NoDisturbingViewController ()

@end

@implementation BanBu_NoDisturbingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self createBackButton];
    [self createSubmitButton];
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
    
    self.title = NSLocalizedString(@"sysPushAlertCloseSetup", nil);
    self.hintLabel.text = self.title;
    self.hintView.layer.borderWidth = 0.8f;
    self.hintView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    self.hintView.backgroundColor = [UIColor colorWithPatternImage:[ThemeManager getThemeImage:@"tablecell_backimage.png"]];
    self.hintView.layer.cornerRadius = 4.0f;
    
    self.beginTime.backgroundColor = [UIColor lightGrayColor];
    self.endTime.backgroundColor = [UIColor whiteColor];
    
    self.fromLabel.text = NSLocalizedString(@"From", nil);
    self.toLabel.text = NSLocalizedString(@"To", nil);
    
    //设置初始化时间
    NSDictionary * settingsDic = [[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"];
    NSArray * timeArray = [settingsDic valueForKey:@"NoDisturbingTime"];
    
    
    if([[timeArray objectAtIndex:0] boolValue])
    {
        self.disturbingSwitch.on = YES;
        self.timeContentView.hidden = NO;
        self.beginTime.text = [timeArray objectAtIndex:1];
        self.endTime.text = [timeArray objectAtIndex:2];
    }
    else
    {
        self.disturbingSwitch.on = NO;
        self.timeContentView.hidden = YES;
    }
    

    self.tap = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setTime:)] autorelease];
    
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setTime:)];
    
    [self.beginTime addGestureRecognizer:self.tap];
    [self.endTime addGestureRecognizer:tap2];
    
    
    self.hourArray = @[@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23"];
    self.minuteArray = @[@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30",@"31",@"32",@"33",@"34",@"35",@"36",@"37",@"38",@"39",@"40",@"41",@"42",@"43",@"44",@"45",@"46",@"47",@"48",@"49",@"50",@"51",@"52",@"53",@"54",@"55",@"56",@"57",@"58",@"59"];
    
    [self setTime:self.tap];
    
    [tap2 release];
}

- (void)createBackButton
{
    BanBu_NavButton *btn_return=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeBack];
    btn_return.position = ButtonPositionLeft;
    [btn_return addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *bar_itemreturn = nil;
    
//    btn_return.frame=CGRectMake(0, 0, 40, 30);
    
    bar_itemreturn=[[[UIBarButtonItem alloc] initWithCustomView:btn_return] autorelease];
    
    self.navigationItem.leftBarButtonItem = bar_itemreturn;
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    MyAppDataManager.noDisturbingControlle = self;
}

//提交按钮
-(void)createSubmitButton
{
    BanBu_NavButton *actionButton=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    actionButton.position = ButtonPositionRight;
    
    CGFloat btnLen = [NSLocalizedString(@"submitButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(100, 30)].width;
    actionButton.titleLabel.font = [UIFont systemFontOfSize:14];
    actionButton.frame=CGRectMake(0, 7, btnLen+20, 30);
    
    [actionButton addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [actionButton setTitle:NSLocalizedString(@"submitButton", nil) forState:UIControlStateNormal];

    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:actionButton]autorelease];
}

//退出
-(void)popself
{
    MyAppDataManager.noDisturbingControlle = nil;
    
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:NO afterShow:0];
    
    [self.navigationController popViewControllerAnimated:YES];
}

//提交设置
-(void)submit
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    
    [self saveTime:self.beginTime.text endTime:self.endTime.text andBool:self.disturbingSwitch.on];
    [self uploadDistorbingTime:self.beginTime.text endTime:self.endTime.text andBool:self.disturbingSwitch.on];
}

//NoDisturbingTime
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.openOrCloseCallBack = nil;
    [_beginTime release];
    [_endTime release];
    [_timePicker2 release];
    [_fromLabel release];
    [_toLabel release];
    [_hintLabel release];
    [_disturbingSwitch release];
    [_timeContentView release];
    [_hintView release];
    [_tap release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [self setBeginTime:nil];
    [self setEndTime:nil];
    [self setTimePicker2:nil];
    [self setFromLabel:nil];
    [self setToLabel:nil];
    [self setHintLabel:nil];
    [self setDisturbingSwitch:nil];
    [self setTimeContentView:nil];
    [self setHintView:nil];
    [super viewDidUnload];
}



#pragma mark -
#pragma mark UIPickerViewDataSource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}


// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return self.hourArray.count;
            break;
            
        case 1:
            return self.minuteArray.count;
            break;
            
        default:
            return 4;
            break;
    }
}

#pragma mark -
#pragma mark UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    switch (component)
    {
        case 0:
            return [self.hourArray objectAtIndex:row];
            break;
        case 1:
            return [self.minuteArray objectAtIndex:row];
            break;
        default:
            return nil;
            break;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (self.setBeginTime)//设置开始时间
    {
        if (component)//分钟
        {
            self.beginTime.text= [self.beginTime.text substringToIndex:2];
            self.beginTime.text = [NSString stringWithFormat:@"%@:%02d",self.beginTime.text,row];
        }
        else//小时
        {
            self.beginTime.text= [self.beginTime.text substringFromIndex:3];
            self.beginTime.text = [NSString stringWithFormat:@"%02d:%@",row,self.beginTime.text];
        }
    }
    else//设置结束时间
    {
        if (component)//分钟
        {
            self.endTime.text= [self.endTime.text substringToIndex:2];
            self.endTime.text = [NSString stringWithFormat:@"%@:%02d",self.endTime.text,row];
        }
        else//小时
        {
            self.endTime.text= [self.endTime.text substringFromIndex:3];
            self.endTime.text = [NSString stringWithFormat:@"%02d:%@",row,self.endTime.text];
        }
    }
}

//当拨动时间选择器时动态调整label显示
-(void)setTime:(UITapGestureRecognizer *)tap
{
    NSInteger tag = tap.view.tag;
    
    if (tag == 1001)//起始时间
    {
        self.beginTime.backgroundColor = [UIColor lightGrayColor];
        self.endTime.backgroundColor = [UIColor whiteColor];
        self.setBeginTime = YES;
        NSInteger hour = [[self.beginTime.text substringToIndex:2] integerValue];
        NSInteger minute = [[self.beginTime.text substringFromIndex:3] integerValue];
        
        [self.timePicker2 selectRow:hour inComponent:0 animated:YES];
        [self.timePicker2 selectRow:minute inComponent:1 animated:YES];
    }
    else//结束时间
    {
        self.beginTime.backgroundColor = [UIColor whiteColor];
        self.endTime.backgroundColor = [UIColor lightGrayColor];
        
        self.setBeginTime = NO;
        NSInteger hour = [[self.endTime.text substringToIndex:2] integerValue];
        NSInteger minute = [[self.endTime.text substringFromIndex:3] integerValue];
        
        [self.timePicker2 selectRow:hour inComponent:0 animated:YES];
        [self.timePicker2 selectRow:minute inComponent:1 animated:YES];
    }
}

#pragma mark -
//保存设置
-(void)saveTime:(NSString *)begnTime endTime:(NSString *)endTime andBool:(BOOL)on
{
    NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
    
    if(on)
    {
        NSArray * timeArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],begnTime,endTime, nil];
        [settingsDic setValue:timeArray forKey:@"NoDisturbingTime"];
        [self setTime:self.tap];
    }
    else
    {
        NSArray * timeArray = [settingsDic valueForKey:@"NoDisturbingTime"];
        if (timeArray != nil)
        {
            self.beginTime.text = [timeArray objectAtIndex:1];
            self.endTime.text = [timeArray objectAtIndex:2];
        }
        else
        {
            self.beginTime.text = @"00:00";
            self.endTime.text = @"00:00";
        }
        
        timeArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:0],begnTime,endTime, nil];//免打扰模式关闭，但是时间要保留
        [settingsDic setValue:timeArray forKey:@"NoDisturbingTime"];
    }
    
    NSMutableDictionary *settingsUpdata = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
    [settingsUpdata setValue:settingsDic forKey:@"settings"];
    [UserDefaults setValue:settingsUpdata forKey:MyAppDataManager.useruid];

}

//提交服务器免打扰时间段
-(void)uploadDistorbingTime:(NSString *)begnTime endTime:(NSString *)endTime andBool:(BOOL)on
{
    NSDictionary * parDic = nil;
    if (on)//开启免打扰
    {
        //本地时间转换为服务器时间
        begnTime = [self changeTimeToServerTime:begnTime];
        endTime = [self changeTimeToServerTime:endTime];
        parDic = [NSDictionary dictionaryWithObjectsAndKeys:begnTime,@"closefrom",endTime,@"closeto", nil];
    }
    else//关闭免打扰
    {
        begnTime = @"00:00:00";
        endTime = @"00:00:00";
        parDic = [NSDictionary dictionaryWithObjectsAndKeys:begnTime,@"closefrom",endTime,@"closeto", nil];
    }
    
    [AppComManager getBanBuData:BanBu_SetPushClose_FromTo par:parDic delegate:self];
}

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    if ([AppComManager respondsDic:resDic isFunctionData:BanBu_SetPushClose_FromTo])
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"zan_success", nil) activityAnimated:NO duration:1.0];
        //                _noDisturbingControlle setOpenOrCloseCallBack:
        if (_openOrCloseCallBack)
        {
            _openOrCloseCallBack(self.disturbingSwitch.on);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }

}
//将本地时间转换为服务器时间
-(NSString *)changeTimeToServerTime:(NSString *)oldTime
{
    //时差为负说明本机时间比服务器时间大，反之本机时间比服务器时间小，（时差为负责转换为服务器时间时应减去时差的绝对值，为正时转换为服务器时间时应加上时差的绝对值）
    NSString * serverTime;
    
    //获取本机时间的时、分
    NSInteger oldHour = [[oldTime substringToIndex:2] integerValue];
    NSInteger oldMinute = [[oldTime substringFromIndex:3] integerValue];
    
    //时差
    NSInteger timeDif = (NSInteger) MyAppDataManager.timeDifference;
    NSInteger hour = timeDif/3600%24;
    NSInteger minute = timeDif%3600/60;
    
    hour = oldHour + hour;
    minute = oldMinute + minute;

    //分钟小与0，向小时借位
    if (minute<0)
    {
        minute = 60 + minute;
        hour -= 1;
    }
    
    //分钟大于0，向小时进位
    if(minute>59)
    {
        hour += minute/60;
        minute = minute%60;
    }
    
    //小时小雨0，向天借位，
    if (hour <0)
    {
        hour = 24+hour;
    }
    
    //小时大于0，想天进位
    if (hour >23)
    {
        hour %= 24;
    }
    
    serverTime = [NSString stringWithFormat:@"%02d:%02d:00",hour,minute];
    
    return serverTime;
}

//设置开启、关闭免打扰模式
- (IBAction)switchAction:(UISwitch *)sender
{
    NSMutableDictionary *settingsDic = [NSMutableDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
    
    if(sender.on)
    {
        self.timeContentView.hidden = NO;
        sender.on = YES;
        NSArray * timeArray = [settingsDic valueForKey:@"NoDisturbingTime"];
        if (timeArray != nil)
        {
            self.beginTime.text = [timeArray objectAtIndex:1];
            self.endTime.text = [timeArray objectAtIndex:2];
        }
        else
        {
            self.beginTime.text = @"00:00";
            self.endTime.text = @"00:00";
        }
        
        [self setTime:self.tap];
    }
    else
    {
        self.timeContentView.hidden = YES;
        sender.on = NO;
    }
}
@end
